package com.fubt.repeat.token.impl;

import javax.servlet.http.Cookie;

import org.apache.commons.lang3.StringUtils;

import com.fubt.repeat.token.TokenManager;
import com.fubt.repeat.web.WebContext;

/**
 * token 存储在Cookie
 * 
 * @author jonathan 2018年3月31日 下午6:00:38
 * @since 1.0.0
 */
public class CookieTokenManager implements TokenManager {

    /**
     * 添加Cookie
     */
    public void add(String key, String value) {

        // -1 表示Cookie永不过期
        WebContext.getHttpServletResponse().addCookie(createCookie(key, value, -1));

    }

    /**
     * 添加Cookie
     */
    public void add(String key, String value, int expiry) {

        WebContext.getHttpServletResponse().addCookie(createCookie(key, value, expiry));

    }

    /**
     * 移除Cookie
     */
    public void remove(String key) {
        Cookie cookie = searchCookieByKey(key);
        if (cookie != null) {
            cookie.setMaxAge(0);
            WebContext.getHttpServletResponse().addCookie(cookie);
        }

    }

    /**
     * 创建cookie
     * 
     * @param key
     * @param value
     * @param expiry
     * @return
     */
    private Cookie createCookie(String key, String value, int expiry) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(expiry);
        return cookie;
    }

    /**
     * 查找Cookie
     * 
     * @param key
     * @return
     */
    private synchronized Cookie searchCookieByKey(String key) {
        Cookie[] cookies = WebContext.getHttpServletRequest().getCookies();
        if (cookies == null) {
            return null;
        } else {

            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), key)) {
                    return cookie;
                }
            }
        }
        return null;

    }

    public String get(String key) {
        Cookie cookie = searchCookieByKey(key);
        if (cookie == null) {
            return "";
        }
        return cookie.getValue();
    }

}
